package com.kj.tms.common.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class FileUtil {
    /**
     * 写文件
     *
     * @param zipElement
     * @param zipFile
     */
    public static File wirteToFile(ZipEntry zipElement, ZipFile zipFile) {
        String fileName = zipElement.getName();
        File ff = new File(zipFile.getName());
        File directory = new File(fileName);
        File file = new File(ff.getParent() + "\\" + fileName);

        String parentName = directory.getParent();
        String newFileName = "";
        if (!"".equals(parentName) && parentName != null) {
            newFileName = ff.getParent() + "\\" + parentName;
        } else {
            newFileName = ff.getParent();
        }
        //创建目录
        File dir = new File(newFileName);
        if (!dir.exists()) {
            dir.mkdir();
        }
        InputStream in = null;
        BufferedReader br = null;
        OutputStreamWriter out = null;
        try {
            in = (InputStream) zipFile.getInputStream(zipElement);

            //读文件
            br = new BufferedReader(new InputStreamReader(in, "UTF-8"));

            //写文件
            out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");

            String line = null;
            while ((line = br.readLine()) != null) {
                out.write(line + "\r\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
                if (br != null) {
                    br.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return file;
    }

    /**
     * 压缩单个文件
     *
     * @param filepath
     * @param zippath
     * @name 中文名称
     * @description 相关说明
     * @time 创建时间:2016年6月23日下午6:48:20
     * @author Administrator
     * @history 修订历史（历次修订内容、修订人、修订时间等）
     */
    public static void ZipFile(String filepath, String zippath) {
        try {
            File file = new File(filepath);
            File zipFile = new File(zippath);
            InputStream input = new FileInputStream(file);
            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            zipOut.putNextEntry(new ZipEntry(file.getName()));
            int temp = 0;
            while ((temp = input.read()) != -1) {
                zipOut.write(temp);
            }
            input.close();
            zipOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 一次性压缩多个文件，文件存放至一个文件夹中
     *
     * @param filepath
     * @param zippath
     * @name 中文名称
     * @description 相关说明
     * @time 创建时间:2016年6月23日下午6:48:40
     * @author Administrator
     * @history 修订历史（历次修订内容、修订人、修订时间等）
     */
    public static void ZipMultiFile(String filepath, String zippath) {
        try {
            File file = new File(filepath);// 要被压缩的文件夹
            File zipFile = new File(zippath);
            InputStream input = null;
            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; ++i) {
                    input = new FileInputStream(files[i]);
                    zipOut.putNextEntry(new ZipEntry(file.getName() + File.separator + files[i].getName()));
                    int temp = 0;
                    while ((temp = input.read()) != -1) {
                        zipOut.write(temp);
                    }
                    input.close();
                }

                for (int i = 0; i < files.length; ++i) {
                    File ff = files[i];
                    deleteFile(ff.getName());
                }
            }
            zipOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Method ZipMultiFileByFileNames
     * @Param [list, zippath]
     * @Return void
     * @Exception
     * @Description [多文件压缩]
     * @Author dsd
     * @Version 1.0
     * @Date 2017/12/13 10:05
     */
    public static void ZipMultiFileByFileNames(List<Map<String, Object>> list, String zippath) {

        try {

            File zipFile = new File(zippath);
            InputStream input = null;
            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            String fileNamePath = null;
            String fileTimeAndNameStr = null;
            for (Map<String, Object> m : list) {
                String fileTime = null;
                String fileName = null;
                for (String k : m.keySet()) {
                    //原文件名
                    if (k.equals("attachmentNameOriginal")) {
                        fileName = m.get(k).toString();
                    }
                    //文件保存路径
                    if (k.equals("saveAddress")) {
                        fileNamePath = m.get(k).toString();
                    }
                    //上传时间
                    if (k.equals("createTime")) {
                        fileTime = m.get(k).toString();
                    }
                }
                fileTimeAndNameStr = fileTime + "_" + fileName;
                input = new FileInputStream(new File(fileNamePath));
                zipOut.putNextEntry(new ZipEntry(fileTimeAndNameStr));
                int temp = 0;
                while ((temp = input.read()) != -1) {
                    zipOut.write(temp);
                }
                input.close();
            }
            zipOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Method ZipMultiFileByFileNames
     * @Param [lstFileNames, zippath,isDel]
     * @Return void
     * @Exception
     * @Description [多文件压缩：是否删除原文件]
     * @Author dsd
     * @Version 1.0
     * @Date 2017/12/13 10:05
     */
    public static void ZipMultiFileByFileNames(List<String> lstFileNames, String zippath, Boolean isDel) {

        try {
            File zipFile = new File(zippath);
            InputStream input = null;
            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            for (int i = 0; i < lstFileNames.size(); i++) {
                String fileName = lstFileNames.get(i);
                String fileNameStr = getFileNameStr(fileName);
                input = new FileInputStream(new File(lstFileNames.get(i)));
                zipOut.putNextEntry(new ZipEntry(fileNameStr));
                int temp = 0;
                while ((temp = input.read()) != -1) {
                    zipOut.write(temp);
                }
                input.close();
            }


            zipOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (isDel) {
                for (int i = 0; i < lstFileNames.size(); i++) {
                    String fileName = lstFileNames.get(i);
                    deleteFile(fileName);
                }
            }
        }
    }


    public static void main(String[] args) {
        //ZipFile("E:/znn/1101011605009735.xml", "E:/znn/ceshi.zip");
        List<String> lstStr = new ArrayList<String>();
        //ZipMultiFile("G:/znnceshi", "G:/znnceshi/ccc.zip");

        lstStr.add("C:/Users/dsd/Desktop/file/2b8696f5faa646799a676739e6a37250.xml");
        lstStr.add("C:/Users/dsd/Desktop/file/0cfcb2d2811b4f5c987c1dd7aa6ff681.xml");

        // ZipMultiFile("C:/Users/dsd/Desktop/file","C:/Users/dsd/Desktop/file/FileDownLoad.zip");
        // ZipMultiFileByFileNames(lstStr, "C:/Users/dsd/Desktop/file/FileDownLoad.zip",false);
    }

    /**
     * 获得文件名
     *
     * @param fileName
     * @return
     */
    public static String getFileNameStr(String fileName) {
        int index = fileName.lastIndexOf(File.separator);
        String fileNameStr = fileName.substring(index + 1);
        return fileNameStr;
    }

    /**
     * 删除文件
     *
     * @param fileName
     */
    public static void deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
    }
}
